{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "23f53670-1a73-46ba-a754-4a497e8e0e64",
   "metadata": {},
   "source": [
    "# The Price is Right\n",
    "\n",
    "## Week 8 Order of Play\n",
    "\n",
    "Day 1: Modal.com and SpecialistAgent  \n",
    "Day 2: RAG, FrontierAgent, Ensemble Agent  \n",
    "Day 3: ScannerAgent, MessengerAgent   \n",
    "Day 4: AutonomousPlannerAgent  \n",
    "Day 5: The Price Is Right Finale\n",
    "\n",
    "\n",
    "Now it's time for the Planning Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9329b9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from openai import OpenAI\n",
    "from dotenv import load_dotenv\n",
    "from agents.scanner_agent import ScannerAgent\n",
    "import chromadb\n",
    "import logging\n",
    "load_dotenv(override=True)\n",
    "openai = OpenAI()\n",
    "MODEL = \"gpt-5.1\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ad465f5",
   "metadata": {},
   "source": [
    "## Start with some test data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8991e888",
   "metadata": {},
   "outputs": [],
   "source": [
    "test_results = ScannerAgent().test_scan()\n",
    "test_results"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb93255d",
   "metadata": {},
   "source": [
    "## Now let's create 3 pretend functions.."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64873072",
   "metadata": {},
   "outputs": [],
   "source": [
    "def scan_the_internet_for_bargains() -> str:\n",
    "    \"\"\" This tool scans the internet for great deals and gets a curated list of promising deals \"\"\"\n",
    "    print(\"Fake function to scan the internet - this returns a hardcoded set of deals\")\n",
    "    return test_results.model_dump_json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af365df5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def estimate_true_value(description: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool estimates the true value of a product based on a text description of it\n",
    "    \"\"\"\n",
    "    print(f\"Fake function to estimating true value of {description[:20]}... - this always returns $300\")\n",
    "    return f\"Product {description} has an estimated true value of $300\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35f15f8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def notify_user_of_deal(description: str, deal_price: float, estimated_true_value: float, url: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool notifies the user of a great deal, given a description of it, the price of the deal, and the estimated true value\n",
    "    \"\"\"\n",
    "    print(f\"Fake function to notify user of {description} which costs {deal_price} and estimate is {estimated_true_value}\")\n",
    "    return \"notification sent ok\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2eda1e45",
   "metadata": {},
   "source": [
    "### Let's try them out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1c4beb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "notify_user_of_deal(\"a new iphone\", 100, 1000, \"https://www.apple.com/iphone\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb5bfdd1",
   "metadata": {},
   "source": [
    "### OK now a big block of JSON"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2be6d141",
   "metadata": {},
   "outputs": [],
   "source": [
    "scan_function = {\n",
    "        \"name\": \"scan_the_internet_for_bargains\",\n",
    "        \"description\": \"Returns top bargains scraped from the internet along with the price each item is being offered for\",\n",
    "        \"parameters\": {\n",
    "            \"type\": \"object\",\n",
    "            \"properties\": {},\n",
    "            \"required\": [],\n",
    "            \"additionalProperties\": False\n",
    "        }\n",
    "    }\n",
    "\n",
    "estimate_function = {\n",
    "    \"name\": \"estimate_true_value\",\n",
    "    \"description\": \"Given the description of an item, estimate how much it is actually worth\",\n",
    "    \"parameters\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"description\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The description of the item to be estimated\"\n",
    "            },\n",
    "        },\n",
    "        \"required\": [\"description\"],\n",
    "        \"additionalProperties\": False\n",
    "    }\n",
    "}\n",
    "\n",
    "notify_function = {\n",
    "    \"name\": \"notify_user_of_deal\",\n",
    "    \"description\": \"Send the user a push notification about the single most compelling deal; only call this one time\",\n",
    "    \"parameters\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"description\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The description of the item itself scraped from the internet\"\n",
    "            },\n",
    "            \"deal_price\": {\n",
    "                \"type\": \"number\",\n",
    "                \"description\": \"The price offered by this deal scraped from the internet\"\n",
    "            }\n",
    "            ,\n",
    "            \"estimated_true_value\": {\n",
    "                \"type\": \"number\",\n",
    "                \"description\": \"The estimated actual value that this is worth\"\n",
    "            }\n",
    "            ,\n",
    "            \"url\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The URL of this deal as scraped from the internet\"\n",
    "            }\n",
    "        },\n",
    "        \"required\": [\"description\", \"deal_price\", \"estimated_true_value\", \"url\"],\n",
    "        \"additionalProperties\": False\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28771d9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [{\"type\": \"function\", \"function\": scan_function},\n",
    " {\"type\": \"function\", \"function\": estimate_function},\n",
    " {\"type\": \"function\", \"function\": notify_function}\n",
    " ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ffb41dd9",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e462e3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def handle_tool_call(message):\n",
    "    \"\"\"\n",
    "    Actually call the tools associated with this message\n",
    "    \"\"\"\n",
    "    results = []\n",
    "    for tool_call in message.tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        arguments = json.loads(tool_call.function.arguments)\n",
    "        tool = globals().get(tool_name)\n",
    "        result = tool(**arguments) if tool else {}\n",
    "        results.append({\"role\": \"tool\",\"content\": json.dumps(result),\"tool_call_id\": tool_call.id})\n",
    "    return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fcc9d254",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_message = \"You find great deals on bargain products using your tools, and notify the user of the best bargain.\"\n",
    "user_message = \"\"\"\n",
    "First, use your tool to scan the internet for bargain deals. Then for each deal, use your tool to estimate its true value.\n",
    "Then pick the single most compelling deal where the price is much lower than the estimated true value, and use your tool to notify the user.\n",
    "Then just reply OK to indicate success.\n",
    "\"\"\"\n",
    "messages = [{\"role\": \"system\", \"content\": system_message},{\"role\": \"user\", \"content\": user_message}]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf42ee15",
   "metadata": {},
   "outputs": [],
   "source": [
    "messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b7e3b29",
   "metadata": {},
   "outputs": [],
   "source": [
    "done = False\n",
    "while not done:\n",
    "    response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)\n",
    "    if response.choices[0].finish_reason==\"tool_calls\":\n",
    "        message = response.choices[0].message\n",
    "        results = handle_tool_call(message)\n",
    "        messages.append(message)\n",
    "        messages.extend(results)\n",
    "    else:\n",
    "        done = True\n",
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b580cd6",
   "metadata": {},
   "source": [
    "## And now.. into an Autonomous Planning Agent\n",
    "\n",
    "And switching the fake functions for REAL functions!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17cfde98",
   "metadata": {},
   "outputs": [],
   "source": [
    "root = logging.getLogger()\n",
    "root.setLevel(logging.INFO)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9d0938d",
   "metadata": {},
   "outputs": [],
   "source": [
    "DB = \"products_vectorstore\"\n",
    "client = chromadb.PersistentClient(path=DB)\n",
    "collection = client.get_or_create_collection('products')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a95bfb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from agents.autonomous_planning_agent import AutonomousPlanningAgent\n",
    "agent = AutonomousPlanningAgent(collection)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e30c66e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.plan()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09e3e5cd",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
